#include "../include/commandStack.h"

int init_command_stack(commandStack_t *pcommandStack){
    bzero(pcommandStack, sizeof(commandStack_t));
    return 0;
}

int is_legal(commandStack_t* stack, const char *value)
{
    printf("value=%s\n",value);
    char path[100]={0};
    get_homedir(path);

    /* printf("Hello\n"); */

    assemble_stack(stack,path);
    strcat(path,value);
    DIR *pdir = opendir(path);
    if(pdir == NULL)
    {
        printf("当前路径非法\n");
        return 0;
    }
    else
    {
        printf("当前路径合法\n");
        closedir(pdir);
        return 1;
    }
}
int push_command_stack(commandStack_t *pcommandStack, const char *value, const int length){
    // 入栈只执行栈操作，是否合法放在业务层做
    /* int tof = is_legal(pcommandStack,value); */
    /* if(tof == 0) */
    /* { */
    /*     return -1; */
    /* } */
    stackNode_t *newNode = (stackNode_t *)calloc(1, sizeof(stackNode_t));
    ERROR_CHECK(newNode, NULL, "stack newNode calloc failed");
    char *data = (char *)malloc(length*sizeof(char));
    //*data = *value; // 错误写法， 只能存第一个字母
    strcpy(data, value);
    
    newNode->data = data;
    
    if(pcommandStack->stackSize == 0){
        pcommandStack->pTop = newNode;
        pcommandStack->pBottom = newNode;
    }
    else{
        pcommandStack->pTop->next = newNode;
        pcommandStack->pTop = newNode;
    }
    pcommandStack->stackSize++;
    return 0;
}

int pop_command_stack(commandStack_t *pcommandStack){
    if(pcommandStack->stackSize == 0){
        printf("stack is empty! pop failed!");
        return -1;
    }
    else if(pcommandStack->stackSize == 1){
        free(pcommandStack->pTop->data);
        free(pcommandStack->pTop);
        pcommandStack->pTop = NULL;
        pcommandStack->pBottom = NULL;
    }
    else{
        stackNode_t *preNode = pcommandStack->pBottom;
        while(preNode->next != pcommandStack->pTop){
            preNode = preNode->next;
        }
        free(pcommandStack->pTop->data);
        free(pcommandStack->pTop);
        pcommandStack->pTop = preNode;
        pcommandStack->pTop->next = NULL;
    }
    pcommandStack->stackSize--;
    return 0;
}
int assemble_stack(const commandStack_t *stack,char buf[])
{
    // 从头结点开始遍历，用strcat把所有节点的数据组装起来
    stackNode_t *cur = stack->pBottom;
    while(cur)
    {
        strcat(buf,cur->data);
        cur = cur->next;
    }
    return 0;
}
int print_stack(const commandStack_t *stack)
{
    stackNode_t *cur = stack->pBottom;
    while(cur)
    {
        printf("%s",cur->data);
        cur = cur->next;
    }
    printf("\n");
    return 0;
}

int clear_stack(commandStack_t *stack){
    if(stack->stackSize == 0){
        return 0;
    }
    while(stack->stackSize){
        pop_command_stack(stack);
    }
    return 0;
}
